import React, { useState } from 'react';
import '../../../../css/maintenan/rusulta.less';
import { PlusOutlined } from '@ant-design/icons';
type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];
import { message, Upload } from 'antd';
import type { GetProp, UploadFile, UploadProps } from 'antd';
import { addResult1 } from '../../../../../../api/csy/api'
import type { DatePickerProps } from 'antd';
import { DatePicker } from 'antd';
import type { Dayjs } from 'dayjs';
import { useNavigate } from 'react-router-dom';

interface props {
  Id: string;
}
// 定义一个名为MaintenanceForm的React函数组件，接收props作为参数
const MaintenanceForm: React.FC<props> = ({ Id }) => {




  const [daily, setDaily] = useState(Id);
  const [rusult, setRusult] = useState('');
  const [time, setTime] = useState('');
  const [name, setName] = useState('');
  const [shebei, setShebei] = useState('');
  const [buwei, setBuwei] = useState('');
  const [content, setContent] = useState('');


  // 定义设备选项
  const deviceOptions = ['CNC机床', '注塑机', '冲压机', '组装线'];
  // 定义部位选项
  const partOptions = ['主轴', '控制系统', '模具', '传送带', '传感器'];

  // 将文件转换为base64格式
  const getBase64 = (file: FileType): Promise<string> =>
    new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = (error) => reject(error);
    });
  const onChange: DatePickerProps<Dayjs[]>['onChange'] = (date, dateString) => {
    setTime(Array.isArray(dateString) ? dateString[0] : dateString);
  };




  // 定义预览状态
  const [previewOpen, setPreviewOpen] = useState(false);
  // 定义预览图片
  const [previewImage, setPreviewImage] = useState('');
  // 定义文件列表
  const [fileList, setFileList] = useState<UploadFile[]>([]);


  // 处理预览
  const handlePreview = async (file: UploadFile) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj as FileType);
    }

    setPreviewImage(file.url || (file.preview as string));
    setPreviewOpen(true);
  };

  // 处理文件变化
  const handleChange: UploadProps['onChange'] = ({ fileList }) =>
    setFileList(fileList);
  // 上传按钮
  const uploadButton = (
    <button style={{ border: 0, background: 'none' }} type="button">
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>Upload</div>
    </button>
  );
  const navigate = useNavigate()
  //保存提交
  const dianji = () => {
    addResult1({ daily, rusult, time, name, shebei, buwei, content }).then((res) => {
      if (res.data.code == 200) {
        message.success('提交成功');
        navigate('/service/Operational/maintenance/DailyMaintenance/indexDaily')
      }
    })
  }

  return (
    <div className="maintenance-form">
      <div className="form-section">
        <label className="required">维修完成照片：</label>
        <div className="file-upload">
          <Upload
            action="http://localhost:3000/csy/upload"
            headers={{
              Authorization: `Bearer ${localStorage.getItem('accessToken')}`,
            }}
            listType="picture-card"
            fileList={fileList}
            onPreview={handlePreview}
            onChange={handleChange}
          >
            {fileList.length >= 8 ? null : uploadButton}
          </Upload>
        </div>
      </div>

      <div className="form-section">
        <label className="required">维修结果：</label>
        <textarea
          value={rusult}
          onChange={((e) => setRusult(e.target.value))}
          placeholder="请输入维修结果"
        />
      </div>

      <div className="form-row">
        <div className="form-section">
          <label className="required">完成时间：</label>
          <DatePicker onChange={onChange} needConfirm />
        </div>
        <div className="form-section">
          <label>记录人员：</label>
          <input type="text" value={name} onChange={(e) => setName(e.target.value)} name="" id="" />
        </div>
      </div>

      <div className="form-row">
        <div className="form-section">
          <label className="required">维修设备：</label>
          <select
            value={shebei}
            onChange={(e) => setShebei(e.target.value)} // 更新维修设备
          >
            <option value="">请选择</option>
            {deviceOptions.map(opt => <option key={opt} value={opt}>{opt}</option>)} // 渲染设备选项
          </select>
        </div>
        <div className="form-section">
          <label className="required">维修部位：</label>
          <select
            value={buwei}
            onChange={(e) => setBuwei(e.target.value)} // 更新维修部位
          >
            <option value="">请选择</option>
            {partOptions.map(opt => <option key={opt} value={opt}>{opt}</option>)} // 渲染部位选项
          </select>
        </div>
      </div>

      <div className="form-section">
        <label className="required">维修内容：</label>
        <textarea
          value={content}
          onChange={(e) => setContent(e.target.value)} // 更新维修内容
          placeholder="请输入维修内容"
        />
      </div>



      <div className="button-group">
        <button className="cancel-button" onClick={() => navigate('/service/Operational/maintenance/DailyMaintenance/indexDaily')}>取消</button>
        <button className="more-button" onClick={dianji}>保存</button>
      </div>
    </div>
  );
};

export default MaintenanceForm;